package com.tyc.flink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.client.program.StreamContextEnvironment;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * 从集合中获取数据
 *
 * @author tyc
 * @version 1.0
 * @date 2022-11-16 15:56:33
 */
public class StreamSourceFromCollection {
    public static void main(String[] args) throws Exception {
        // 注意这里环境是流处理环境
        StreamExecutionEnvironment env = StreamContextEnvironment.getExecutionEnvironment();
        // 获取数据源
        DataStream<String> inputDataStream = env.fromCollection(Arrays.asList("hello a","a aaa","c bbb"));
        SingleOutputStreamOperator<org.apache.flink.api.java.tuple.Tuple2<String, Integer>> result = inputDataStream.flatMap(new MyStreamFlatMap())
                // 根据二元组的第一个元素分组
                .keyBy(item -> item.f0)
                // 根据二元组的第二个元素汇总
                .sum(1);
        result.print();
        env.execute();
    }

    private static class MyStreamFlatMap implements FlatMapFunction<String, org.apache.flink.api.java.tuple.Tuple2<String, Integer>> {
        @Override
        public void flatMap(String s, Collector<org.apache.flink.api.java.tuple.Tuple2<String, Integer>> collector) throws Exception {
            String[] words = s.split(" ");
            for(String word:words) {
                collector.collect(new Tuple2<>(word,1));
            }
        }
    }
}
